package com.caigou.handler;


import com.caigou.enums.ResponseEnum;
import com.caigou.exception.DuplicateDataException;
import com.caigou.exception.ForbiddenAccountException;
import com.caigou.exception.TokenVerificationFailedException;
import com.caigou.exception.UserNotFoundException;
import com.caigou.util.Result;
import com.caigou.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;


/**
 * @Author: 杨忠强
 * @Date: 2018/7/19 16:13
 * @Description:
 */

@Slf4j
@ControllerAdvice
public class ExceptionHandle {
    /**
     * 捕获全局异常,防止返回500错误码
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result handle(RuntimeException e) {

        if (e instanceof AccessDeniedException) {
            //用户登录需要返回401状态即可,无需打印日志
            //log.error(e.getMessage(), e);
            return ResultUtil.error(ResponseEnum.NO_ACCESS.getCode(), ResponseEnum.NO_ACCESS.getMessage());
        }
        if (e instanceof DataIntegrityViolationException) {
            log.error(e.getMessage(), e);
            return ResultUtil.error(ResponseEnum.SERVER_ERROR.getCode(), ResponseEnum.SERVER_ERROR.getMessage());
        }
        if (e instanceof HttpMessageNotReadableException) {
            log.error(e.getMessage(), e);
            return ResultUtil.error(ResponseEnum.PARAM_ERROR.getCode(), ResponseEnum.PARAM_ERROR.getMessage());
        }
        if (e instanceof UserNotFoundException) {
            //用户登录需要返回401状态即可,无需打印日志
            //log.error(e.getMessage(), e);
            return ResultUtil.error(ResponseEnum.NO_TOKEN.getCode(), ResponseEnum.NO_TOKEN.getMessage());
        }
        if (e instanceof DuplicateDataException) {
            log.error(e.getMessage(), e);
            return ResultUtil.error(ResponseEnum.DUPLICATE_KEYWORD_ERROR.getCode(), ResponseEnum.DUPLICATE_KEYWORD_ERROR.getMessage());
        }
        if (e instanceof ForbiddenAccountException) {
            log.error(e.getMessage(), e);
            return ResultUtil.error(ResponseEnum.FORBIDDEN_ACCOUNT.getCode(), ResponseEnum.FORBIDDEN_ACCOUNT.getMessage());
        }


        if (e instanceof TokenVerificationFailedException) {
            log.error(e.getMessage(), e);
            return ResultUtil.error(ResponseEnum.TOKEN_VERIFICATION_FAILED.getCode(), ResponseEnum.TOKEN_VERIFICATION_FAILED.getMessage());
        }

        else {
            log.error("[系统异常] {}", e);
            return ResultUtil.error(ResponseEnum.SERVER_ERROR.getCode(), ResponseEnum.SERVER_ERROR.getMessage());
        }


    }


}
